<?php
function run_blast_protein($wd,$seq,$ecut,$org,$ref) {
    $v = getP3DBVersion();
    $fasta = $wd."data/pro.$org.$ref.$v";
    if (!file_exists($fasta)) {
        write_fasta_protein($org,$ref,$fasta);
        run_formatdb($wd, $fasta);
    }
    return run_blast($wd,$seq,$ecut,$fasta);
}

function write_fasta_protein($org,$ref,$dir) {
    $query  = "SELECT id,sequence FROM protein WHERE 1";
    if (!empty($org)) {
        $query .= " AND organism='$org'";
    }

    if (!empty($ref)) {
        $query .= " AND EXISTS (".
                  "SELECT * FROM proteinDataSourceRelation ".
                  "WHERE protein.id=proteinDataSourceRelation.protein AND dataSource=$ref)";
    }
    
    $result = mysql_query($query) or die($query.'--Error, query failed');
    $fhandle = fopen($dir, "w");
    while ($row = mysql_fetch_array($result)) {
        fwrite($fhandle, ">{$row['id']}\n{$row['sequence']}\n");
    }
    fclose($fhandle);
}

function run_blast_nr_peptide($wd,$seq,$ecut,$org,$ref) {
    $v = getP3DBVersion();
    $fasta = $wd."data/nrpep.$org.$ref.$v";
    if (!file_exists($fasta)) {
        write_fasta_nr_peptide($org,$ref,$fasta);
        run_formatdb($wd, $fasta);
    }
    return run_blast($wd,$seq,$ecut,$fasta);
}

function write_fasta_nr_peptide($org,$ref,$dir) {
    $query = "SELECT DISTINCT phosphoSequence,sequence,protein,location FROM peptide WHERE 1";
    if (!empty($org)) {
        $query .= " AND '$org'=(SELECT organism FROM protein WHERE protein.id=peptide.protein)";
    }
    if (!empty($ref)) {
        $query .= " AND '$ref'=(SELECT dataSource FROM mass WHERE mass.id=peptide.mass)";
    }

    $result = mysql_query($query) or die($query.'--Error, query failed');
    $fhandle = fopen($dir, "w");
    while ($row = mysql_fetch_array($result)) {
        fwrite($fhandle, ">{$row['phosphoSequence']}|{$row['protein']}|{$row['location']}\n{$row['sequence']}\n");
    }
    fclose($fhandle);
}

function run_blast($wd,$seq,$ecut,$fasta) {
        $seqfile = tempnam($wd."tmp", "seq_");
        $fhandle = fopen($seqfile, "w");
        fwrite($fhandle, $seq);
        fclose($fhandle);

        $blastout = tempnam($wd."tmp", "blast_result_"); //TODO
        
        $command = $wd."blastall -p blastp -F F -v 100 -b 100 -i $seqfile -o $blastout -e $ecut -d $fasta";
//        echo $command;
        exec($command);

//        chmod ($seqfile,0777);
        unlink($seqfile); //delete seqeunce file
        return $blastout;
}

function run_formatdb($wd,$dir) {
    //write_fasta($org,$ref,$dir);
    $command = $wd."formatdb -i $dir";
//    echo $command;
    exec($command);
}

?>
